package com.scale.service.voice.controller;

import com.example.common.result.Result;
import com.example.conversation.vo.MessageVO;
import com.example.voice.dto.ProcessMessageDTO;
import com.example.voice.dto.SpeechToTextDTO;
import com.example.voice.dto.TextToSpeechDTO;
import com.example.voice.dto.UploadUserAudioDTO;
import com.example.voice.dto.CompleteVoiceFlowDTO;
import com.example.voice.vo.SpeechToTextVO;
import com.example.voice.vo.TextToSpeechVO;
import com.example.voice.vo.UploadUserAudioVO;
import com.example.voice.vo.UserAudioUploadResultVO;
import com.example.voice.vo.CompleteVoiceFlowVO;
import com.scale.service.voice.service.VoiceProcessService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 语音处理 前端控制器
 * </p>
 *
 * @author crp
 * @since 2025-09-24
 */
@Api(tags = "语音处理")
@RestController
@RequestMapping("/api/voice")
@CrossOrigin(origins = {
    "http://localhost:3000", 
    "http://127.0.0.1:3000", 
    "http://localhost:3001", 
    "http://127.0.0.1:3001", 
    "http://localhost:5173", 
    "http://127.0.0.1:5173"
}, maxAge = 3600, allowedHeaders = "*", allowCredentials = "true", methods = {RequestMethod.GET, RequestMethod.POST, RequestMethod.OPTIONS})
public class VoiceFilesController {

    @Autowired
    private VoiceProcessService voiceProcessService;

    /**
     * 语音转文字
     */
    @ApiOperation("语音转文字")
    @PostMapping("/speech-to-text")
    public Result<SpeechToTextVO> speechToText(
            @ApiParam("语音转文字请求") @RequestBody @Validated SpeechToTextDTO speechToTextDTO) {
        
        SpeechToTextVO result = voiceProcessService.speechToText(speechToTextDTO);
        return Result.success(result);
    }

    /**
     * 文字转语音
     */
    @ApiOperation("文字转语音")
    @PostMapping("/text-to-speech")
    public Result<TextToSpeechVO> textToSpeech(
            @ApiParam("文字转语音请求") @RequestBody @Validated TextToSpeechDTO textToSpeechDTO) {
        
        TextToSpeechVO result = voiceProcessService.textToSpeech(textToSpeechDTO);
        return Result.success(result);
    }

    /**
     * 完整语音对话流程
     * 包括：语音转文字 -> 获取AI回复 -> 文字转语音
     */
    @ApiOperation("完整语音对话流程")
    @PostMapping("/process-message")
    public Result<MessageVO> processMessage(
            @ApiParam("语音对话请求") @RequestBody @Validated ProcessMessageDTO processMessageDTO) {
        
        MessageVO result = voiceProcessService.processVoiceMessage(processMessageDTO);
        return Result.success(result);
    }

    /**
     * 完整录音流程（推荐使用）
     * 包括：上传录音 -> 语音识别 -> 发送消息 -> AI回复 -> 语音合成
     */
    @ApiOperation("完整录音流程")
    @PostMapping("/complete-voice-flow")
    public Result<CompleteVoiceFlowVO> completeVoiceFlow(
            @ApiParam("完整录音流程请求") @RequestBody @Validated CompleteVoiceFlowDTO completeVoiceFlowDTO) {
        
        try {
            // 1. 上传用户录音
            UploadUserAudioDTO uploadDTO = new UploadUserAudioDTO();
            uploadDTO.setAudioData(completeVoiceFlowDTO.getAudioData());
            uploadDTO.setFormat(completeVoiceFlowDTO.getFormat());
            uploadDTO.setUserId(completeVoiceFlowDTO.getUserId());
            uploadDTO.setConversationId(completeVoiceFlowDTO.getConversationId());
            
            UploadUserAudioVO uploadResult = voiceProcessService.uploadUserAudio(uploadDTO);
            if (!uploadResult.getSuccess()) {
                return Result.error("录音上传失败: " + uploadResult.getErrorMessage());
            }
            
            // 2. 语音识别
            SpeechToTextDTO sttDTO = new SpeechToTextDTO();
            sttDTO.setAudioData(completeVoiceFlowDTO.getAudioData());
            sttDTO.setLanguage(completeVoiceFlowDTO.getLanguage());
            sttDTO.setEnableEmotionDetection(completeVoiceFlowDTO.getEnableEmotionDetection());
            
            SpeechToTextVO sttResult = voiceProcessService.speechToText(sttDTO);
            if (sttResult.getIsMock() != null && sttResult.getIsMock()) {
                return Result.error("语音识别失败，请检查API配置或音频格式");
            }
            
            // 3. 发送消息并获取AI回复
            ProcessMessageDTO processDTO = new ProcessMessageDTO();
            processDTO.setCharacterId(completeVoiceFlowDTO.getCharacterId());
            processDTO.setAudioData(completeVoiceFlowDTO.getAudioData());
            processDTO.setFormat(completeVoiceFlowDTO.getFormat());
            processDTO.setConversationId(completeVoiceFlowDTO.getConversationId());
            processDTO.setUserId(completeVoiceFlowDTO.getUserId());
            processDTO.setUserVoiceUrl(uploadResult.getVoiceUrl()); // 设置用户录音URL
            
            MessageVO aiReply = voiceProcessService.processVoiceMessage(processDTO);
            
            // 4. 构建完整响应
            CompleteVoiceFlowVO result = new CompleteVoiceFlowVO();
            result.setUserVoiceUrl(uploadResult.getVoiceUrl());
            result.setUserVoiceSize(uploadResult.getFileSize());
            result.setUserVoiceDuration(uploadResult.getDuration());
            result.setRecognizedText(sttResult.getText());
            result.setConfidence(sttResult.getConfidence());
            result.setEmotionType(sttResult.getEmotionType());
            result.setEmotionIntensity(sttResult.getEmotionIntensity());
            result.setAiReply(aiReply);
            result.setIsMock(sttResult.getIsMock());
            
            return Result.success("录音处理完成", result);
            
        } catch (Exception e) {
            return Result.error("录音处理失败: " + e.getMessage());
        }
    }

    /**
     * 上传用户录音文件
     */
    @ApiOperation("上传用户录音文件")
    @PostMapping("/upload-user-audio")
    public Result<UserAudioUploadResultVO> uploadUserAudio(
            @ApiParam("用户录音上传请求") @RequestBody @Validated UploadUserAudioDTO uploadUserAudioDTO) {
        
        try {
            UploadUserAudioVO result = voiceProcessService.uploadUserAudio(uploadUserAudioDTO);
            if (result.getSuccess()) {
                // 转换为前端需要的简化格式
                UserAudioUploadResultVO simpleResult = new UserAudioUploadResultVO();
                simpleResult.setVoiceUrl(result.getVoiceUrl());
                simpleResult.setFileSize(result.getFileSize());
                simpleResult.setDuration(result.getDuration());
                
                return Result.success("上传成功", simpleResult);
            } else {
                return Result.error("录音上传失败: " + result.getErrorMessage());
            }
        } catch (Exception e) {
            return Result.error("录音上传异常: " + e.getMessage());
        }
    }
}

